namespace Billing
{
    using AjaxControlToolkit;
    using ICSharpCode.SharpZipLib.Zip;
    using Billing.Controls;
    using System;
    using System.Data;
    using System.IO;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.Security.Application;

    public class DownloadBillReport : Page
    {
        protected Button BtnDownload;
        protected ConfirmButtonExtender BtnDownload_ConfirmButtonExtender;
        protected Button BtnRetrieve;
        protected HyperLink HyperLink1;
        protected DropDownList ddlBillPeriod;
        protected DropDownList ddlCostCentre;
        protected DropDownList ddlAgency;
        protected DropDownList ddlBU;
        private DataTable dt;
        protected GridView gvwReports;
        protected Label lblAvailable;
        protected Label lblCC;
        protected Label lblAgency;
        protected Label lblBU;
        protected ucHighlight ucHighlight1;
        protected ucPageTitle ucPageTitle1;
        protected UpdatePanel updatePanel1;
        protected UpdatePanel updatePanel2;
        protected UpdatePanel updatePanel7;
        protected UpdateProgress updateprogress1;

        private void BindBillPeriod()
        {
            ClsBillPeriod cls1 = new ClsBillPeriod();
            if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
            {
                //this.ddlBillPeriod.DataSource = cls1.SelectReleasedPeriodByBillingRecipientEmail(LoginUser.Email);
                this.ddlBillPeriod.DataSource = cls1.SelectReleasedPeriodByCostCentre(LoginUser.CostCentreID);
            }
            else
            {
                this.ddlBillPeriod.DataSource = cls1.SelectReleasedPeriodByBUID(LoginUser.BUID);
            }
            this.ddlBillPeriod.DataTextField = "ServiceMonth";
            this.ddlBillPeriod.DataValueField = "ID";
            this.ddlBillPeriod.DataBind();
            DataTable dtCurrentPeriod = cls1.SelectCurrentPreiod();
            if ((dtCurrentPeriod.Rows != null) && (dtCurrentPeriod.Rows.Count > 0))
            {
                this.BillPeriodID = dtCurrentPeriod.Rows[0]["ID"].ToString();
            }
        }

        private void BindDLLCostCentre()
        {
            ClsCostCentresInBU cls = new ClsCostCentresInBU();
            if (this.ddlBU.SelectedIndex <= 0)
            {
                cls.BUID = 0;
            }
            else
            {
                cls.BUID = Convert.ToInt64(this.ddlBU.SelectedValue);
            }
            DataTable dt1 = cls.SelectByBUID();
            this.ddlCostCentre.Items.Clear();
            this.ddlCostCentre.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlCostCentre.Items.Add(new ListItem(Encoder.HtmlEncode(dt1.Rows[i]["CostCentreIDName"].ToString()), Encoder.HtmlEncode(dt1.Rows[i]["ID"].ToString())));
            }
        }

        private void BindDLLAgency()
        {
            DataTable dt1 = new ClsAgency().SelectAll();
            this.ddlAgency.Items.Clear();
            this.ddlAgency.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlAgency.Items.Add(new ListItem(Encoder.HtmlEncode(dt1.Rows[i]["AgencyIDName"].ToString()), Encoder.HtmlEncode(dt1.Rows[i]["ID"].ToString())));
            }
            this.BindDLLBUsInAgency();
        }

        private void BindDLLBUsInAgency()
        {
            ClsBUsInAgency cls = new ClsBUsInAgency();
            if (this.ddlAgency.SelectedIndex <= 0)
            {
                cls.AgencyID = 0;
            }
            else
            {
                cls.AgencyID = Convert.ToInt64(this.ddlAgency.SelectedValue);
            }
            DataTable dt1 = cls.SelectByAgencyID();
            this.ddlBU.Items.Clear();
            this.ddlBU.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlBU.Items.Add(new ListItem(Encoder.HtmlEncode(dt1.Rows[i]["BUIDName"].ToString()), Encoder.HtmlEncode(dt1.Rows[i]["ID"].ToString())));
            }
            this.BindDLLCostCentre();
        }

        private DataTable BindGridViewData()
        {
            ClsBillReportRepository cls1 = new ClsBillReportRepository();
            if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
            {
                this.dt = cls1.SelectAllReleasedWithoutDataByPeriodLoginGroupLoginEmailBillCustomer(Convert.ToInt64(this.BillPeriodID), LoginUser.GroupID, LoginUser.Email, LoginUser.CostCentreID);
            }
            else
            {
                this.dt = cls1.SelectAllReleasedWithoutDataByPeriodLoginGroupLoginBUAgencyBUCC(Convert.ToInt64(this.BillPeriodID), LoginUser.GroupID, LoginUser.BUID, Convert.ToInt64(this.ddlAgency.SelectedValue), Convert.ToInt64(this.ddlBU.SelectedValue), Convert.ToInt64(this.ddlCostCentre.SelectedValue));
            }
            if (this.dt != null)
            {
                this.gvwReports.DataSource = this.dt;
                this.gvwReports.DataBind();
                if (this.dt.Rows.Count == 0)
                {
                    this.lblAvailable.Visible = false;
                    this.BtnDownload.Visible = false;
                    this.ucHighlight1.Message = "No report available for current selection.";
                }
                else
                {
                    this.lblAvailable.Visible = true;
                    this.BtnDownload.Visible = this.Read0;
                }
            }
            return this.dt;
        }

        protected void BtnDownload_Click(object sender, EventArgs e)
        {
            int iCheckCount = 0;
            foreach (GridViewRow row in this.gvwReports.Rows)
            {
                CheckBox chkbox = (CheckBox) row.FindControl("GRChkBox");
                if (chkbox.Checked)
                {
                    iCheckCount++;
                }
            }
            if (iCheckCount == 0)
            {
                this.ucHighlight1.ErrorMessage = "Please select at least one report for processing";
            }
            else
            {
                string strFile = ClsUtilityHelper.GenerateId();
                ZipOutputStream zipOS = new ZipOutputStream(File.Create(base.Server.MapPath("./") + strFile + ".zip"));
                zipOS.SetLevel(9);
                ClsBillReportRepository ClsRepo = new ClsBillReportRepository();
                foreach (GridViewRow row in this.gvwReports.Rows)
                {
                    CheckBox chk1 = (CheckBox) row.FindControl("GRChkBox");
                    if (chk1.Checked)
                    {
                        Label lblRepoID = (Label) row.FindControl("lblRepositoryID");
                        ClsRepo.ID = Convert.ToInt64(lblRepoID.Text);
                        DataTable dt1 = ClsRepo.Select();
                        if ((dt1 != null) && (dt1.Rows.Count > 0))
                        {
                            byte[] bytes = (byte[])dt1.Rows[0]["ReportData"];
                            //byte[] bytes = new byte[0];
                            //string filename = Server.MapPath("/") + "temp/" + dt1.Rows[0]["ReportFileName"].ToString();
                            //using (FileStream fs = new FileStream(filename, FileMode.Open))
                            //{
                            //    bytes = new byte[fs.Length];
                            //    fs.Read(bytes, 0, bytes.Length);
                            //}

                            ZipEntry zipEntry = new ZipEntry(dt1.Rows[0]["ReportFileName"].ToString());
                            zipOS.PutNextEntry(zipEntry);
                            zipOS.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                zipOS.Finish();
                zipOS.Close();
                base.Response.ClearContent();
                base.Response.Clear();
                base.Response.ContentType = "application/zip";
                base.Response.AppendHeader("Content-Disposition", "attachment; filename=download.zip;");
                base.Response.TransmitFile(base.Server.MapPath("./") + strFile + ".zip");
                base.Response.Flush();
                base.Response.Close();
                if (File.Exists(base.Server.MapPath("./") + strFile + ".zip"))
                {
                    File.Delete(base.Server.MapPath("./") + strFile + ".zip");
                }
            }
        }

        protected void BtnRetrieve_Click(object sender, EventArgs e)
        {
            this.BindGridViewData();
            this.HyperLink1.Visible = true;
        }

        protected void ddlAgency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlAgency.SelectedIndex != -1)
            {
                this.BindDLLBUsInAgency();
            }
        }

        protected void ddlBU_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlBU.SelectedIndex != -1)
            {
                this.BindDLLCostCentre();
            }
        }

        private void GetPermission()
        {
            ClsACLHelper cls = new ClsACLHelper();
            string pageName = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx";
            cls.SetPermission(LoginUser.TreeMenu, pageName);
            this.Read0 = cls.Read0;
            this.BtnRetrieve.Visible = cls.Read0;
            if (!cls.Read0)
            {
                base.Response.Redirect("logout.aspx", true);
            }
        }

        protected void GRChkALL_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkALL = (CheckBox) this.gvwReports.HeaderRow.FindControl("GRChkALL");
            foreach (GridViewRow row in this.gvwReports.Rows)
            {
                CheckBox chk1 = (CheckBox) row.FindControl("GRChkBox");
                if (chkALL.Checked)
                {
                    chk1.Checked = true;
                }
                else
                {
                    chk1.Checked = false;
                }
            }
        }

        protected void GRChkBox_CheckedChanged(object sender, EventArgs e)
        {
            bool bAllChecked = true;
            CheckBox chk1 = (CheckBox) sender;
            CheckBox chkALL = (CheckBox) this.gvwReports.HeaderRow.FindControl("GRChkALL");
            if (!chk1.Checked)
            {
                chkALL.Checked = false;
            }
            else if (chk1.Checked)
            {
                foreach (GridViewRow row in this.gvwReports.Rows)
                {
                    CheckBox chk2 = (CheckBox) row.FindControl("GRChkBox");
                    if (!chk2.Checked)
                    {
                        bAllChecked = false;
                    }
                }
                if (bAllChecked)
                {
                    chkALL.Checked = true;
                }
            }
        }

        protected void gvwReports_Sorting(object sender, GridViewSortEventArgs e)
        {
            this.dt = new DataView(this.BindGridViewData()) { Sort = e.SortExpression + " " + this.ViewState["SortDirection"].ToString() }.ToTable();
            if (this.ViewState["SortDirection"].ToString() == "ASC")
            {
                this.ViewState["SortDirection"] = "DESC";
            }
            else
            {
                this.ViewState["SortDirection"] = "ASC";
            }
            this.gvwReports.DataSource = this.dt;
            this.gvwReports.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ucHighlight1.CloseAll();
            if (this.Session["BUID"] == null)
            {
                base.Response.Redirect("default.aspx", true);
            }
            if (!this.Page.IsPostBack)
            {
                this.ViewState["SortDirection"] = "ASC";
                this.BindBillPeriod();
                this.SetVisibleBillingRecipientRelatedComponent();
                if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
                {
                }
                else
                {
                    this.BindDLLAgency();
                    if (LoginUser.BUID > 0)
                    {
                        this.ddlAgency.SelectedValue = LoginUser.AgencyID.ToString();
                        this.BindDLLBUsInAgency();
                        this.ddlBU.SelectedValue = LoginUser.BUID.ToString();
                        this.BindDLLCostCentre();
                        this.ddlAgency.Enabled = false;
                        this.ddlBU.Enabled = false;
                    }
                }
                this.GetPermission();
            }
        }

        private void SetVisibleBillingRecipientRelatedComponent()
        {
            bool xVisible = false;
            if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
            {
                xVisible = true;
            }
            else
            {
                xVisible = false;
            }
            this.lblAgency.Visible = !xVisible;
            this.ddlAgency.Visible = !xVisible;
            this.lblBU.Visible = !xVisible;
            this.ddlBU.Visible = !xVisible;
            this.lblCC.Visible = !xVisible;
            this.ddlCostCentre.Visible = !xVisible;
        }

        public string BillPeriodID
        {
            get
            {
                if (this.ddlBillPeriod.SelectedIndex == -1)
                {
                    return "0";
                }
                return this.ddlBillPeriod.SelectedValue;
            }
            set
            {
                this.ddlBillPeriod.SelectedIndex = -1;
                if ((value != "") && (value != "0"))
                {
                    this.ddlBillPeriod.SelectedIndex = this.ddlBillPeriod.Items.IndexOf(this.ddlBillPeriod.Items.FindByValue(value));
                }
            }
        }

        public bool Read0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xRead0"]);
            }
            set
            {
                this.ViewState["xRead0"] = value;
            }
        }
    }
}
